package com.sanyang.lawyer.controller;

import com.sanyang.lawyer.utils.FastDFSutils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@RestController
@RequestMapping("fastdfs")
public class FastDFS_demo {

    @Autowired
    private FastDFSutils fastDFSutils;


    //文件上传测试
    @RequestMapping("uploadfile")
    public String uploadfile(MultipartRequest request){
        //将响应对象装换为文件对象
        HttpServletRequest request1 = (HttpServletRequest)request;

        //获取数据从request1 中获取
        String username = request1.getParameter("username");
        System.out.println(username);

        //文件对象
        MultipartFile file = request.getFile("file");

        //返回的是文件路径
        String filepath = null;
        try {
            filepath = fastDFSutils.uploadfile(file);
        } catch (Exception e) { 
            e.printStackTrace();
        }
        return filepath;
    }

    //文件下载测试
    @RequestMapping("download")
    public void downloadFile(String fileUrl, HttpServletResponse response) throws Exception {
        System.out.println(fileUrl);
        byte[] bytes = fastDFSutils.downloadfile(fileUrl);
        // 这里只是为了整合fastdfs，所以写死了文件格式。需要在上传的时候保存文件名。下载的时候使用对应的格式
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("测试.jpg", "UTF-8"));
        response.setCharacterEncoding("UTF-8");
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            outputStream.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    //文件删除
    @RequestMapping("deletefile")
    public String deleteFile(String filepath){
        return fastDFSutils.deletefile(filepath);
    }



}
